package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.controller.webSocket.WebSocketServer;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Value("${sky.shop.address}")
    private String shopAddress;

    @Value("${sky.baidu.ak}")
    private String ak;
    @Autowired
    private WebSocketServer webSocketServer;
    @Override
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        checkOutOfRange(addressBook.getCityName()+addressBook.getDistrictName()+addressBook.getDetail());
        Long currentId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(currentId);
        List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);
        if (list == null) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        Orders orders = new Orders();
        orders.setNumber(String.valueOf(System.currentTimeMillis()));

        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setUserId(currentId);
        orders.setAddressBookId(addressBook.getId());
        orders.setOrderTime(LocalDateTime.now());
        orders.setAddress(addressBook.getDetail());
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        // orders.setConsignee(addressBook.getConsignee());
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setPayStatus(Orders.UN_PAID);
        //向订单表插入一条数据
        orderMapper.insert(orders);
        //向订单明细表插入多条数据
        List<OrderDetail> orderDetailslist = new ArrayList<>();
        for (ShoppingCart cart : list) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailslist.add(orderDetail);
            orderDetailMapper.insert(orderDetail);
        }
        //清楚购物车
        shoppingCartMapper.clean(currentId);
        Map map = new HashMap();
        map.put("type", 1);//消息类型，1表示来单提醒
        map.put("orderId", orders.getId());
        map.put("content", "订单号：" + orders.getNumber());

        //通过WebSocket实现来单提醒，向客户端浏览器推送消息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
        OrderSubmitVO orderVO = new OrderSubmitVO();
        orderVO.setId(orders.getId());
        orderVO.setOrderNumber(orders.getNumber());
        orderVO.setOrderAmount(orders.getAmount());
        orderVO.setOrderTime(orders.getOrderTime());
        return orderVO;


    }

    @Override
    public PageResult history(int page, int pageSize, Integer status) {
        PageHelper.startPage(page, pageSize);
        OrdersPageQueryDTO pageQueryDTO = new OrdersPageQueryDTO();
        pageQueryDTO.setUserId(BaseContext.getCurrentId());
        pageQueryDTO.setStatus(status);
        //分页查询
        Page<Orders> list = orderMapper.Page(pageQueryDTO);
        List<OrderVO> orderVOList = new ArrayList<>();
        if (list != null) {
            for (Orders orders : list) {
                Long id = orders.getId();
                List<OrderDetail> orderDetail = orderDetailMapper.selectById(id);
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetail);
                orderVOList.add(orderVO);
            }
        }
        return new PageResult(list.getTotal(), orderVOList);
    }

    @Override
    public OrderVO selectByOrderId(Long id) {
        List<OrderDetail> orderDetails = orderDetailMapper.selectById(id);
        Orders orders = orderMapper.selectById(id);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetails);
        return orderVO;
    }

    @Override
    public void CancelByOrderId(Long id) {
        Orders orders = orderMapper.selectById(id);
        if (orders.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders order = new Orders();
        order.setId(orders.getId());
        if (orders.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            //退款
            order.setPayStatus(Orders.REFUND);
        }
        order.setStatus(Orders.CANCELLED);
        order.setCancelReason("用户取消");
        order.setCancelTime(LocalDateTime.now());
        orderMapper.update(order);

    }

    @Override
    public void addByOrderId(Long id) {
        Orders orders = orderMapper.selectById(id);
        Long currentId = BaseContext.getCurrentId();
        List<OrderDetail> orderDetails = orderDetailMapper.selectById(id);
        for (OrderDetail orderDetail : orderDetails) {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail, shoppingCart, String.valueOf(id));
            shoppingCart.setUserId(currentId);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartMapper.insert(shoppingCart);
        }
        //ShoppingCart shoppingCart=new ShoppingCart();


    }

    @Override
    public PageResult condition(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());

        Page<Orders> page = orderMapper.Page(ordersPageQueryDTO);


        List<OrderVO> orderVOList = new ArrayList<>();
        if (page != null) {
            for (Orders orders : page) {
                Long id = orders.getId();
                List<OrderDetail> orderDetail = orderDetailMapper.selectById(id);
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetail);
                orderVOList.add(orderVO);
            }

        }
        return new PageResult(page.getTotal(), orderVOList);
//    @Override
//    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
//        Long userId = BaseContext.getCurrentId();
//        User user = userMapper.getById(userId);
//
//        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
//
//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException("该订单已支付");
//        }
//
//        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
//        vo.setPackageStr(jsonObject.getString("package"));
//
//        return vo;
//    }
//
//    @Override
//    public void paySuccess(String outTradeNo) {
//        Long userId = BaseContext.getCurrentId();
//
//        // 根据订单号查询当前用户的订单
//        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo, userId);
//
//        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
//        Orders orders = Orders.builder()
//                .id(ordersDB.getId())
//                .status(Orders.TO_BE_CONFIRMED)
//                .payStatus(Orders.PAID)
//                .checkoutTime(LocalDateTime.now())
//                .build();
//
//        orderMapper.update(orders);
//    }
    }

    @Override
    public OrderStatisticsVO statistics() {
       Integer toBeConfirmed=orderMapper.select(Orders.TO_BE_CONFIRMED);
       Integer Confirmed=orderMapper.select(Orders.CONFIRMED);
       Integer deliveryInProgress=orderMapper.select(Orders.DELIVERY_IN_PROGRESS);
   return new OrderStatisticsVO(toBeConfirmed,Confirmed,deliveryInProgress);
    }

    @Override
    public void ReceiveOrder(OrdersConfirmDTO confirmDTO) {
        Orders orders = orderMapper.selectById(confirmDTO.getId());
        orders.setStatus(Orders.CONFIRMED);
        orderMapper.update(orders);

    }



    @Override
    public void CancelOrder(OrdersCancelDTO ordersCancelDTO) {
        Orders orders = orderMapper.selectById(ordersCancelDTO.getId());
        if (!(orders.getStatus()==3)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orderse=new Orders();
        orderse.setStatus(Orders.CANCELLED);
        orderse.setId(orders.getId());
        orderse.setRejectionReason(ordersCancelDTO.getCancelReason());
        orderMapper.update(orderse);
    }

    /**
     * 完成订单
     * @param id
     */
    @Override
    public void complete(Long id) {
        Orders orders = orderMapper.selectById(id);
        if (!orders.getStatus().equals(Orders.DELIVERY_IN_PROGRESS) || orders==null){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders order=new Orders();
        order.setId(orders.getId());
        order.setStatus(Orders.COMPLETED);
        order.setDeliveryTime(LocalDateTime.now());
        orderMapper.update(order);

    }

    @Override
    public void RejectOrder(OrdersRejectionDTO ordersRejectionDTO) {
        Orders orders = orderMapper.selectById(ordersRejectionDTO.getId());
        if (!(orders.getStatus()==2)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orderse=new Orders();
        orderse.setStatus(Orders.CANCELLED);
        orderse.setId(orders.getId());
        orderse.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orderMapper.update(orderse);
    }

    @Override
    public void deliver(Long id) {
        Orders orders = orderMapper.selectById(id);
        if (! orders.getStatus().equals(Orders.CONFIRMED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orderse=new Orders();
        orderse.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderse.setId(orders.getId());

        orderMapper.update(orderse);

    }




    private void checkOutOfRange(String address) {
        Map map = new HashMap();
        map.put("address",shopAddress);
        map.put("output","json");
        map.put("ak",ak);

        //获取店铺的经纬度坐标
        String shopCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        JSONObject jsonObject = JSON.parseObject(shopCoordinate);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("店铺地址解析失败");
        }

        //数据解析
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        String lat = location.getString("lat");
        String lng = location.getString("lng");
        //店铺经纬度坐标
        String shopLngLat = lat + "," + lng;

        map.put("address",address);
        //获取用户收货地址的经纬度坐标
        String userCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        jsonObject = JSON.parseObject(userCoordinate);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("收货地址解析失败");
        }

        //数据解析
        location = jsonObject.getJSONObject("result").getJSONObject("location");
        lat = location.getString("lat");
        lng = location.getString("lng");
        //用户收货地址经纬度坐标
        String userLngLat = lat + "," + lng;

        map.put("origin",shopLngLat);
        map.put("destination",userLngLat);
        map.put("steps_info","0");

        //路线规划
        String json = HttpClientUtil.doGet("https://api.map.baidu.com/directionlite/v1/driving", map);

        jsonObject = JSON.parseObject(json);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("配送路线规划失败");
        }

        //数据解析
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray jsonArray = (JSONArray) result.get("routes");
        Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");

        if(distance > 5000){
            //配送距离超过5000米
            throw new OrderBusinessException("超出配送范围");
        }

    }
    @Override
    public void checkTimeAndStatus() {
        LocalDateTime time=LocalDateTime.now().plusMinutes(-15);
        List<Long>ids=orderMapper.selectTimeAndStatus(Orders.PENDING_PAYMENT,time);
        if (ids!=null &&ids.size()>0){
            for (int i = 0; i < ids.size(); i++) {

                orderMapper.update(Orders.builder().id(ids.get(i)).status(Orders.CANCELLED).cancelReason("用户付款超时").build());
            }

        }
    }

    @Override
    public void checkTimeAndStatusComplete() {
        LocalDateTime time=LocalDateTime.now().plusMinutes(-60);
        List<Long>ids=orderMapper.selectTimeAndStatus(Orders.DELIVERY_IN_PROGRESS,time);
        if (ids!=null &&ids.size()>0){
            for (int i = 0; i < ids.size(); i++) {

                orderMapper.update(Orders.builder().id(ids.get(i)).status(Orders.COMPLETED).build());
            }

        }
    }

    @Override
    public void reminder(Long id) {
        Orders orders = orderMapper.selectById(id);
        if (orders==null){
            throw  new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Map map=new HashMap();
        map.put("type", 2);//2代表用户催单
        map.put("orderId", id);
        map.put("content", "订单号：" + orders.getNumber());

        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }
}